<?php

date_default_timezone_set("PRC");
// 如果前端开启了 withCredentials: true, 则下面的2个配置项目必须设置，且Access-Control-Allow-Origin不能为*,必须指定一个URL，
// 如： header('Access-Control-Allow-Origin: http://tcms.localhost/');
// header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Origin: *');
// 控制允许的method
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
// 控制允许的headers * 允许全部，或者直接指定允许的头
// 如：header('Access-Control-Allow-Headers: SSE-TOKEN, TOKEN, Origin, Content-Type, X-Requested-With, Authorization');
header('Access-Control-Allow-Headers: *');
header("Cache-Control: no-store");
header("Cache-Control: no-cache");
header("Cache-Control: private");
header("Content-Type: text/event-stream");

$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId == 0) {
	$lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
}

if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') >= 0) {
	echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
	echo "retry: 2000\n";
}

// event-stream
$i = $lastEventId;
$c = $i + 100;
while (++$i < $c) {
	echo "id: " . $i . "\n";
	echo "data: " . $i . ";\n\n";
	ob_flush();
	flush();
	sleep(1);
}

?>